package com.sgb.kjwl.view.ui.activity.material;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;

import com.alibaba.fastjson.JSONObject;
import com.blankj.utilcode.util.SPUtils;
import com.google.gson.reflect.TypeToken;
import com.google.android.material.tabs.TabLayout;

import com.sgb.alimaplibrary.MapLocationTools;
import com.sgb.capital.utils.DialogHelper;
import com.sgb.capital.utils.SPreferenceUtil;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ActivityGoodsAggregateBinding;
import com.sgb.kjwl.model.entity.home.UpdateIndexEvent;
import com.sgb.kjwl.view.ui.adapter.CommPagerAdapter2;
import com.sgb.kjwl.viewmodel.material.GoodsAggregateViewModel;
import com.swgk.core.common.base.BaseViewModel;
import com.swgk.core.view.entity.MenuEntity;
import com.swgk.core.event.EventConstant;
import com.sgb.link.event.MaterialEvent;
import com.sgb.kjwl.view.ui.activity.supplier3.NewSupplierFragment;
import com.sgb.kjwl.view.ui.fragment.home.GoodsCompanyFragment;
import com.swgk.core.base.model.entity.RequestCode;
import com.swgk.core.mmkvutil.CacheMarker;
import com.sgb.kjwl.view.ui.fragment.home.GoodsMainGoodsListFragment3;
import com.sgb.kjwl.view.ui.fragment.home.GoodsMainGoodsListFragment4;
import com.sgb.kjwl.view.ui.fragment.material.SupplierCollectionFragment;
import com.swgk.core.base.BaseFragment;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.mmkvutil.MkvUtils;
import com.swgk.core.mmkvutil.DatalUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.Serializable;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;

/**
 * 商品大集合界面
 * 五花八门
 *
 * @author Administrator
 */
public class GoodsAggregateActivity extends AppActivity {
    @SuppressLint("StaticFieldLeak")
    private static View view;
    private static View viewCover;
    private ActivityGoodsAggregateBinding binding;
    private double locCurrentLat = 0;
    private double locCurrentLong = 0;
    private boolean isMap;
    private MapLocationTools mapLocationTools;
    private String hyid = "";
    /**
     * 全部商品
     */
    private GoodsMainGoodsListFragment3 allGoodsFragment;
    /**
     * 自营商品
     */
    private GoodsMainGoodsListFragment3 selfEmployedGoodsFragment;
    /**
     * 促销商品
     */
    private GoodsMainGoodsListFragment4 promotionalGoods;
    /**
     * 热销商品
     */
    private GoodsMainGoodsListFragment4 isSellGoodGoods;
    /**
     * 企业专项
     */
    private GoodsCompanyFragment goodsCompanyFragment;
    /**
     * 三级分类的id
     */
    private String firstCategoryId, secondCategoryId, thirdCategoryId;

    private List<MenuEntity> menuEntities = new ArrayList<>();


    private  int currentIndex = 0;


    private GoodsAggregateViewModel mViewModel;

    /**
     * 商品首页 相似商品跳转
     *
     * @param context          上下文对象
     * @param object           顶部TAb标题的集合
     * @param position         当前顶部tab展示的下标
     * @param firstCategoryId  第一级分类选中的Id 可以为"",但是不能为Null
     * @param secondCategoryId 第二级分类选中的Id 可以为Null，表示不指定二级分类筛选
     * @param thirdCategoryId  第三级分类选中的Id 可以为Null，表示不指定三级分类筛选
     * @param isMap            是否显示地图
     */
    public static void start(Context context, Object object, int position,
                             @NonNull String firstCategoryId, @Nullable String secondCategoryId, @Nullable String thirdCategoryId, boolean isMap) {
        Intent intent = new Intent();
        Bundle bundle = new Bundle();
        bundle.putSerializable("object", (Serializable) object);
        bundle.putInt("position", position);
        bundle.putString("one", firstCategoryId);
        bundle.putString("two", secondCategoryId);
        bundle.putString("three", thirdCategoryId);
        bundle.putBoolean("isMap", isMap);
        intent.putExtras(bundle);
        intent.setClass(context, GoodsAggregateActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        context.startActivity(intent);
    }

    /**
     * 商品首页 相似商品跳转
     *
     * @param context          上下文对象
     * @param object           顶部TAb标题的集合
     * @param position         当前顶部tab展示的下标
     * @param firstCategoryId  第一级分类选中的Id 可以为"",但是不能为Null
     * @param secondCategoryId 第二级分类选中的Id 可以为Null，表示不指定二级分类筛选
     * @param thirdCategoryId  第三级分类选中的Id 可以为Null，表示不指定三级分类筛选
     * @param isMap            是否显示地图
     */
    public static void start(Context context, Object object, int position,
                             @NonNull String firstCategoryId, @Nullable String secondCategoryId, @Nullable String thirdCategoryId, boolean isMap,String hyid) {
        Intent intent = new Intent();
        Bundle bundle = new Bundle();
        bundle.putSerializable("object", (Serializable) object);
        bundle.putInt("position", position);
        bundle.putString("one", firstCategoryId);
        bundle.putString("two", secondCategoryId);
        bundle.putString("three", thirdCategoryId);
        bundle.putBoolean("isMap", isMap);
        bundle.putString("hyid",hyid);
        intent.putExtras(bundle);
        intent.setClass(context, GoodsAggregateActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        context.startActivity(intent);
    }


    @Override
    protected boolean statusBarDark() {
        return false;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {

    }

    @Override
    protected void initView() {
        if(!EventBus.getDefault().isRegistered(this)){
            EventBus.getDefault().register(this);
        }

        binding = DataBindingUtil.setContentView(GoodsAggregateActivity.this, R.layout.activity_goods_aggregate);
        mViewModel  = new ViewModelProvider(this).get(GoodsAggregateViewModel.class);
        binding.setViewModel(mViewModel);
        binding.setLifecycleOwner(this);
        menuEntities = (List<MenuEntity>) getIntent().getSerializableExtra("object");
        currentIndex = getIntent().getIntExtra("position", 0);
        firstCategoryId = getIntent().getStringExtra("one");
        secondCategoryId = getIntent().getStringExtra("two");
        thirdCategoryId = getIntent().getStringExtra("three");
        isMap = getIntent().getBooleanExtra("isMap", false);
        hyid = getIntent().getStringExtra("hyid");
        if(menuEntities==null||menuEntities.size()==0) {
            if(!TextUtils.isEmpty(SPUtils.getInstance().getString(SPreferenceUtil.SAVE_GOODS_TiTLE))){
                menuEntities = JSONObject.parseArray(SPUtils.getInstance().getString(SPreferenceUtil.SAVE_GOODS_TiTLE),MenuEntity.class);
                initFragment(menuEntities, getCacheMenuEntity(), currentIndex);
            }else {
                mViewModel.recommendMenu();
            }
        }else{
            initFragment(menuEntities, getCacheMenuEntity(), currentIndex);
        }
        mViewModel.listdata.observe(this,listdata ->{
            initFragment(listdata, getCacheMenuEntity(), currentIndex);
        });

        mViewModel.mLoading.observe(this,intdata->{
            switch (intdata){
                case BaseViewModel.SHOW_LODING:
                    DialogHelper.showProgressDialog(this, null, "获取信息中...", 0, false, null).setCanceledOnTouchOutside(false);
                    break;
                case BaseViewModel.DISMISS_LODING:
                    DialogHelper.dismissProgressDialog();
                    break;
            }
        });

        binding.ivBack.setOnClickListener(this);
        view = binding.layoutPop;
        viewCover = binding.viewCover;
        initMap();
        initShanyan();
        for (int i = 0; i < binding.tablayout.getTabCount(); i++) {
            TabLayout.Tab tab = binding.tablayout.getTabAt(i);
            if (tab != null) {
                tab.setCustomView(getTabView(i, menuEntities));
            }
        }
        binding.tablayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                updateTabTextView(tab, true);
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
                updateTabTextView(tab, false);
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
        updateTabTextView(binding.tablayout.getTabAt(binding.tablayout.getSelectedTabPosition()), true);
    }


    /**
     * 从缓存中获取三级商品分类数据
     *
     * @return 三级分类数据
     */
    private List<MenuEntity<MenuEntity<MenuEntity>>> getCacheMenuEntity() {
        Type type = new TypeToken<List<MenuEntity<MenuEntity<MenuEntity>>>>() {
        }.getType();
        Object object = DatalUtils.getInstance().getData(MkvUtils.CacheModular, CacheMarker.CacheGoodsCategoryModel, type);
        if (object != null) {
            List<MenuEntity<MenuEntity<MenuEntity>>> cacheList = (List<MenuEntity<MenuEntity<MenuEntity>>>) object;
            DatalUtils.getInstance().putData(MkvUtils.CacheModular, CacheMarker.CacheGoodsCategoryModel, "");
            return cacheList;
        } else {
            return null;
        }
    }

    private void updateTabTextView(TabLayout.Tab tab, boolean isSelect) {
        if (tab == null || tab.getCustomView() == null) {
            return;
        }
        if (isSelect) {
            //选中加粗
            TextView tabSelect = (TextView) tab.getCustomView().findViewById(R.id.tv_tab_item_textview);
            tabSelect.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
            tabSelect.setTextColor(getResources().getColor(R.color.white));
            tabSelect.setTextSize(18);
            tabSelect.setText(tab.getText());
        } else {
            TextView tabUnSelect = (TextView) tab.getCustomView().findViewById(R.id.tv_tab_item_textview);
            tabUnSelect.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
            tabUnSelect.setTextColor(getResources().getColor(R.color.white));
            tabUnSelect.setTextSize(15);
            tabUnSelect.setText(tab.getText());
        }
    }


    private View getTabView(int currentPosition, List<MenuEntity> table) {
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.tab_item_textview, null);
        TextView textView = (TextView) view.findViewById(R.id.tv_tab_item_textview);
        textView.setTextColor(getResources().getColor(R.color.white));
        textView.setTextSize(15);
        textView.setText(table.get(currentPosition).getName());
        return view;
    }

    private void initFragment(List<MenuEntity> tableMenuEntity, List<MenuEntity<MenuEntity<MenuEntity>>> goodsType, int currentIndex) {
        ArrayList<BaseFragment> fragmentList = new ArrayList<>();
        if (tableMenuEntity == null || tableMenuEntity.size() == 0) {
            return;
        }
        ListIterator<MenuEntity> iterator = tableMenuEntity.listIterator();
        while (iterator.hasNext()) {
            MenuEntity menuEntity1 = iterator.next();
            String nameId = menuEntity1.getId();
            if ("29".equals(nameId)) {
                if (currentIndex == 0) {
                    allGoodsFragment = GoodsMainGoodsListFragment3.newInstance(1, goodsType, firstCategoryId, secondCategoryId, thirdCategoryId, false, false, true,hyid);
                } else {
                    allGoodsFragment = GoodsMainGoodsListFragment3.newInstance(1, goodsType, "", null, null, false, false, true,hyid);
                }

                fragmentList.add(allGoodsFragment);
            } else if ("26".equals(nameId)) {
                //地图
                iterator.remove();
            } else if ("32".equals(nameId)) {
                //自营商品
                if (currentIndex == 1) {
                    selfEmployedGoodsFragment = GoodsMainGoodsListFragment3.newInstance(1, goodsType, firstCategoryId, secondCategoryId, thirdCategoryId, true, false, true);
                } else {
                    selfEmployedGoodsFragment = GoodsMainGoodsListFragment3.newInstance(1, goodsType, "", null, null, true, false, true);
                }
                fragmentList.add(selfEmployedGoodsFragment);
            } else if ("24".equals(nameId)) {
                //集采商品
                fragmentList.add(SupplierCollectionFragment.newInstance(1, "1"));
            } else if ("30".equals(nameId)) {
                //促销商品
                if (currentIndex == 3) {
                    promotionalGoods = GoodsMainGoodsListFragment4.newInstance(1, goodsType, firstCategoryId, secondCategoryId, thirdCategoryId, true, false,hyid);
                } else {
                    promotionalGoods = GoodsMainGoodsListFragment4.newInstance(1, goodsType, "", null, null, true, false,hyid);
                }
                fragmentList.add(promotionalGoods);
                //热销商品
            } else if ("34".equals(nameId)) {
                if (currentIndex == 4) {
                    isSellGoodGoods = GoodsMainGoodsListFragment4.newInstance(1, goodsType, firstCategoryId, secondCategoryId, thirdCategoryId, false, true,"-2");
                } else {
                    isSellGoodGoods = GoodsMainGoodsListFragment4.newInstance(1, goodsType, "", null, null, false, true,"-2");
                }
                fragmentList.add(isSellGoodGoods);
            } else if ("31".equals(nameId)) {
                //供应商
                fragmentList.add(NewSupplierFragment.newInstance(isMap,null, "1"));
            } else if ("35".equals(nameId)) {
                //企业专项
                goodsCompanyFragment =GoodsCompanyFragment.newInstance(1, goodsType, "", null, null, false, false, true,hyid);
                goodsCompanyFragment = GoodsCompanyFragment.newInstance(1, goodsType, "", null, null, false, false, true);
                fragmentList.add(goodsCompanyFragment);
            } else if ("23".equals(nameId)) {
                iterator.remove();
            } else if ("2".equals(nameId)) {
                //发布询价
                iterator.remove();
            } else if ("36".equals(nameId)) {
                iterator.remove();
            }
        }
        CommPagerAdapter2 goodsFragmentPagerAdapter = new CommPagerAdapter2(getSupportFragmentManager(), fragmentList, tableMenuEntity);
        binding.viewpager.setAdapter(goodsFragmentPagerAdapter);
        binding.tablayout.setupWithViewPager(binding.viewpager);
//        binding.viewpager.setOffscreenPageLimit(fragmentList.size());
        binding.viewpager.setCurrentItem(currentIndex);
    }

    /**
     * 获取一级分类数据
     *
     * @param menuEntityList 三级分类数据
     * @return 第一级商品分类的数据（不包含"全部"分类）
     */
    private List<MenuEntity> filterFirstCategoryMenuEntity(List<MenuEntity<MenuEntity<MenuEntity>>> menuEntityList) {
        if (menuEntityList == null || menuEntityList.size() == 0) {
            return null;
        }
        List<MenuEntity> menuEntities = new ArrayList<>();
        for (MenuEntity<MenuEntity<MenuEntity>> menuEntity : menuEntityList) {
            if ("".equals(menuEntity.getId())) {
                continue;
            }
            MenuEntity menuEntity1 = new MenuEntity();
            menuEntity1.setDatas(menuEntity.getDatas());
            menuEntity1.setUrl(menuEntity.getUrl());
            menuEntity1.setSelected(menuEntity.isSelected());
            menuEntity1.setParentId(menuEntity.getParentId());
            menuEntity1.setName(menuEntity.getName());
            menuEntity1.setImageResource(menuEntity.getImageResource());
            menuEntity1.setId(menuEntity.getId());
            menuEntity1.setIconContent(menuEntity.getIconContent());
            menuEntity1.setHostImg(menuEntity.getHostImg());
            menuEntity1.setAppIconUrl(menuEntity.getAppIconUrl());
            menuEntity1.setAppIcon(menuEntity.getAppIcon());
            menuEntities.add(menuEntity1);
        }
        return menuEntities;
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.iv_back) {
            finish();
        }
    }

    private void initMap() {
        if (mapLocationTools == null) {
            mapLocationTools = new MapLocationTools(getApplicationContext());
            mapLocationTools.initLocation(false);
        }
        mapLocationTools.setLocationListener((address, Longitude, Latitude) -> {
            //此处的BDLocation为定位结果信息类，通过它的各种get方法可获取定位相关的全部结果
            //以下只列举部分获取经纬度相关（常用）的结果信息
            //更多结果信息获取说明，请参照类参考中BDLocation类中的说明
            locCurrentLat = Latitude;    //获取纬度信息
            locCurrentLong = Longitude;    //获取经度信息
            EventBus.getDefault().postSticky(MaterialEvent.make().setMessageTag(EventConstant.EVENT_GOODS_LOC).setMessageData(locCurrentLat + "").setObject(locCurrentLong + ""));
        });
        mapLocationTools.startLocation();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == RequestCode.REQUEST_SHOP) {
            String[] threeLevelClassificationId = getThreeLevelClassificationId(data);
            if (threeLevelClassificationId != null) {
                allGoodsFragment.setCurrentItem(threeLevelClassificationId[0], threeLevelClassificationId[1], threeLevelClassificationId[2]);
            }
        } else if (resultCode == RESULT_OK && requestCode == RequestCode.REQUEST_SHOP_SELFEMPLOYED) {
            String[] threeLevelClassificationId = getThreeLevelClassificationId(data);
            if (threeLevelClassificationId != null) {
                selfEmployedGoodsFragment.setCurrentItem(threeLevelClassificationId[0], threeLevelClassificationId[1], threeLevelClassificationId[2]);
            }
        } else if (resultCode == RESULT_OK && requestCode == RequestCode.REQUEST_SHOP_PROMOTION) {
            String[] threeLevelClassificationId = getThreeLevelClassificationId(data);
            if (threeLevelClassificationId != null) {
                promotionalGoods.setCurrentItem(threeLevelClassificationId[0], threeLevelClassificationId[1], threeLevelClassificationId[2]);
            }
        } else if (resultCode == RESULT_OK && requestCode == RequestCode.REQUEST_SHOP_SELL_GOOD) {
            String[] threeLevelClassificationId = getThreeLevelClassificationId(data);
            if (threeLevelClassificationId != null) {
                isSellGoodGoods.setCurrentItem(threeLevelClassificationId[0], threeLevelClassificationId[1], threeLevelClassificationId[2]);
            }
        } else if (resultCode == RESULT_OK && requestCode == RequestCode.REQUEST_SHOP_COMPANY) {
            String[] threeLevelClassificationId = getThreeLevelClassificationId(data);
            if (threeLevelClassificationId != null) {
                goodsCompanyFragment.setCurrentItem(threeLevelClassificationId[0], threeLevelClassificationId[1], threeLevelClassificationId[2]);
            }
        }
    }

    private String[] getThreeLevelClassificationId(Intent data) {
        if (data == null) {
            return null;
        }
        String[] levelId = new String[3];
        String firstCategoryId = data.getStringExtra("twoLevelClassId");
        String secondCategoryId = data.getStringExtra("threeLevelClassId");
        String thirdCategoryId = data.getStringExtra("fourLevelClassId");
        levelId[0] = firstCategoryId;
        levelId[1] = secondCategoryId;
        levelId[2] = thirdCategoryId;
        return levelId;
    }

    public static View getPopView() {
        return view;
    }

    public static View getCoverView() {
        return viewCover;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(EventBus.getDefault().isRegistered(this)){
            EventBus.getDefault().unregister(this);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void updateIndexPosition(UpdateIndexEvent event){
        if(event!=null) {
            binding.tablayout.postDelayed(new Runnable() {
                @Override
                public void run() {
                    binding.tablayout  .getTabAt(event.getIndexposition()).select();
                }
            },100);
        }
    }

}